var app = getApp();
var api = require('../../api.js');
var is_loading_more = false;
var is_no_more = false;
var util = require('../../utils/util.js');
var timer;
var socketOpen = false;
var frameBuffer_Data, session;
var icon = true;
var collect = true;
var pusherWin = true;
let socketMsgQueue = [];
var heartBeatFailCount = 0; // 心跳失败次数
var heartBeatTimeOut = null; // 终止心跳
var heart = '';
var timeoutObj;
var serverTimeoutObj;
var msgSendTimeoutObj;
var queue_timer, play_timer;
var system_queue = [],
  reward_queue = [],reward_ids=[];

import ROP from '../../dms/dms.js';
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {

    currentTab: 0,
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },
    video_id: 0,
    flag: true, //打赏弹窗参数
    flag2: true,
    show_input_password: true, //输入密码弹窗
    showOrHidden: false,
    clickevent: false,
    playIcon: "../../images/live-win01.png",
    collectIcon: "../../images/ic-like00.png",
    playPusher: "../../images/pusher-play.png",
    pusher: true,
    comment_data: '', //评论输入
    comment_img: "", //评论图片
    video_password: '', //密码
    isShowToast: false,
    collect_loading: false,
    c_id: 0,
    img_list: [],
    content: '',
    comment_count: 0,
    goods_loading: -1,
    page: 1,
    // show:false,
    show_modal: false,
    comment_list: [],
    scrollTop: 600,
    scrollHeight: 300,

    iscounting: false, //倒计时
    reward_count: 0,
    reward_list: [],
    fullScreen: 0,
    orientation: "vertical",
    useronload: false,
    videoContext: {},
    liveContent: {},
    scroll_top: 0,
    current_comment_index: '',
    comment_ids: [],
    urls: [],
    for_video_id: 0,
    lockReconnect: false,
    HiddenShare: true,
    HiddenShare1: true,
    pubkey: 'pub_2ef431a14f6d147e5942b0c7f03bcb6a',
    subkey: 'sub_43254df680e7f58d0334166b6b7ea396'
  },

  enter: function () {
    var page = this
    setTimeout(function () {
      console.log('连接：' + page.data.video_id + '_' + wx.getStorageSync('openid'))
      ROP.Enter(page.data.video.pubkey, page.data.video.subkey, page.data.video_id + '_' + wx.getStorageSync('openid'))
      page.subscribe()

    }, 100)
  },
  subscribe: function () {
    var that = this
    var page = this
    ROP.Subscribe(that.data.video.app_id + '_' + that.data.video.id)
    setTimeout(() => {
      console.log('Subscribe' + that.data.video.app_id + '_' + that.data.video.id);

      page.initConnect()
      // ROP.GETSTATUS();
    }, 300)
  },
  initConnect() {
    var page = this
    app.request({
      url: api.aodian.connect,
      method: "post",
      data: {
        id: page.data.video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {

        }
      },
      complete: function (res) {}
    });
  },
  disconnect: function () {
    console.log('leave')
    setTimeout(function () {
      ROP.Leave()
    }, 100)

    this.closeROP()
  },
  closeROP() {
    var page = this
    app.request({
      url: api.aodian.close,
      method: "post",
      data: {
        id: page.data.video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {}
      },
      complete: function (res) {}
    });
  },


  HiddenShareContent: function () {
    this.setData({
      HiddenShare: true
    })
  },

  popup1: function () {
    this.setData({
      HiddenShare: false
    })
  },

  GeneratePosters: function () {
    this.setData({
      HiddenShare: true
    })

  },
  ClosePosters: function () {
    this.setData({
      HiddenShare1: true
    })
  },

  //关闭切换小窗口图标函数
  tapVoicePlay: function () {
    if (icon) this.setData({
      playIcon: "../../images/live-win02.png"
    });
    else this.setData({
      playIcon: "../../images/live-win01.png"
    });
    icon = !icon;
  },

  togglePusher: function () {
    var pusher = this.data.pusher;
    this.setData({
      pusher: !this.data.pusher
    })
  },

  pusherPlay: function () {
    if (pusherWin) this.setData({
      playPusher: "../../images/pusher-pause.png"
    });
    else this.setData({
      playPusher: "../../images/pusher-play.png"
    });
    pusherWin = !pusherWin;
  },
  /**
   * 退出全屏
   */
  onExitFullScreen() {
    var page = this
    this.data.liveContext.exitFullScreen({
      direction: 0,
      success: function (res) {
        page.setData({
          fullScreen: 0
        })
      }

    })
  },

  //收藏事件
  collect: function () {
    var page = this;
    app.request({
      url: api.user.collect,
      method: 'POST',
      data: {
        video_id: page.data.video_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          var video_tmp = page.data.video;
          if (page.data.video.collect == true) {
            video_tmp.collect = false;
            page.setData({
              video: video_tmp
            });
            wx.showToast({
              title: '取消收藏',
              icon: 'success'
            });

          } else {
            video_tmp.collect = true;
            page.setData({
              video: video_tmp
            });
            wx.showToast({
              title: '收藏成功',
              icon: 'success'
            });
          }
        } else {
          wx.showModal({
            title: '警告',
            content: res.msg,
            showCancel: false
          })
        }
      }
    });
    // if (collect) this.setData({ collectIcon: "../../images/ic-like11.png" });
    // else this.setData({ collectIcon: "../../images/ic-like00.png" });
    // collect = !collect;
  },

  //navbar，菜单切换
  tabFun: function (e) {
    //获取触发事件组件的dataset属性  
    var _datasetId = e.target.dataset.id;
    console.log("----" + _datasetId + "----");
    var _obj = {};
    _obj.curHdIndex = _datasetId;
    _obj.curBdIndex = _datasetId;
    this.setData({
      tabArr: _obj
    });
  },


  //打赏弹窗的显示与隐藏
  showpop: function () {
    this.setData({
      flag: false
    })
  },
  //输入密码弹窗显示
  showPasswordPop: function () {
    this.setData({
      show_input_password: false
    })
  },
  hidePasswordPop: function () {
    this.setData({
      show_input_password: true
    })
  },
  //消失

  hidepop: function () {
    this.setData({
      flag: true
    })
  },
  showpop2: function () {
    this.setData({
      flag: true,
      flag2: false
    })
  },
  tolivepay: function () {
    this.setData({
      flag2: false
    })
  },
  //消失
  hidepop2: function () {
    this.setData({
      flag2: true,
      othermoney: ''
    })
  },





  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // //判断登陆

    is_loading_more = false;
    is_no_more = false;
    var page = this;

    if (options) {
      var tmp_options = wx.getStorageSync("tmp_options");
      if (tmp_options) {
        wx.setStorageSync("tmp_options", Object.assign(tmp_options, options))
      } else {
        wx.setStorageSync("tmp_options", options)
      }
      var id = options.id;
      if (options.scene) {
        var scene = decodeURIComponent(options.scene);
        scene = app.str2Obj(scene);
        console.log(scene)
        this.setData({
          video_id: scene.video_id
        })
      }
      if (options.uid) {
        var uid = options.uid;
        if (uid) {
          page.agent(uid);
        }
      }
      if (options.for_video_id) {
        this.setData({
          for_video_id: options.for_video_id
        })
      }
      if (options.video_id) {
        this.setData({
          video_id: options.video_id
        })
      }

    }

    var time = util.formatdate(new Date());
    page.setData({
      time: time,
      store: wx.getStorageSync('store'),
      user_info: wx.getStorageSync('user_info')
    });
    this.getVideoInfo();

    // console.log(page);
    // share.init(page);
    // comment.init(page);
    this.startQueue()
    wx.getSystemInfo({
      success(res) {
        page.setData({
          sys_info: res,
          second_height: res.windowHeight - 210 - 44 - 48
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var page = this;
    this.ctx = wx.createLivePlayerContext('player');
    //连接成功
    ROP.On("enter_suc", function () {

      console.log('EnterSuc');
      // setText("EnterSuc");
    })
    //离线，以及开始重连的事件
    ROP.On("reconnect", function () {
      console.log('reconnect');
      page.initConnect()
      // setText("reconnect:");
    })
    ROP.On("offline", function (err) {
      console.log('offline' + err);
      // setText("offline:" + err);
    })
    //收到关注的话题的消息
    ROP.On("publish_data", function (data, topic) {
      page.getMsg(data);
      console.log("recv at " + topic + " -> " + data)
    })
    //连接失败
    ROP.On("enter_fail", function (err) {
      console.log("EnterFail:" + err);
    })
    //被相同ID挤掉线。
    ROP.On("connectold", function () {
      console.log("Losed");
    })
    //与服务器断开连接的事件
    ROP.On("losed", function () {
      page.closeROP()
      console.log("Losed");
    })

  },
  /**
   * 弹幕
   */
  addBarrage() {
    const barrageComp = this.selectComponent('.barrage')
    this.barrage = barrageComp.getBarrageInstance({
      font: 'bold 16px sans-serif',
      duration: 20,
      lineHeight: 2,
      mode: 'separate',
      padding: [10, 0, 10, 0],
      tunnelShow: false
    })
    this.barrage.open()

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // if (app.globalData.localSocket.readyState !== 0 && app.globalData.localSocket.readyState !== 1) {
    //   console.log('开始尝试连接WebSocket！readyState=' + app.globalData.localSocket.readyState)
    //   if (this.data.video) {
    //     this.webSocket();

    //   }


    // }
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    this.startQueue();
  },

  //购买
  buyVideo: function () {
    var page = this;
    let pay_video_id
    if (page.data.for_video_id > 0) {
      pay_video_id = page.data.for_video_id
    } else {
      pay_video_id = page.data.video_id
    }
    var video = page.data.video;
    wx.showModal({
      title: '提示',
      content: '是否购买？',
      success: function (e) {
        if (e.confirm) {
          wx.showLoading({
            title: '提交中',
          });

          app.request({
            url: api.order.video,
            method: 'POST',
            data: {
              video_id: pay_video_id,
              //price: page.data.video_pay.price
            },
            success: function (res) {
              console.log(res);
              if (res.errcode == 0) {
                app.request({
                  url: api.order.get_pay_data,
                  method: 'POST',
                  data: {
                    order_id: res.data.order_id,
                    pay_type: 'WECHAT_PAY'
                  },
                  success: function (result) {
                    wx.hideLoading();
                    if (result.errcode == 0) {
                      var pay_data = result.data;
                      wx.requestPayment({
                        timeStamp: pay_data.timeStamp,
                        nonceStr: pay_data.nonceStr,
                        package: pay_data.package,
                        signType: pay_data.signType,
                        paySign: pay_data.paySign,
                        success: function (res) {
                          wx.showToast({
                            title: '订单支付成功',
                            icon: 'success'
                          });
                          setTimeout(function () {
                            //page.getVideoInfo();
                            video.AUTH = true;
                            page.setData({
                              video: video
                            });
                            page.playVideo();
                          }, 2000)
                        },
                        fail: function (res) {
                          wx.showToast({
                            title: '订单未支付',
                            image: '/images/icon-warning.png'
                          });
                        }
                      });
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: result.msg,
                        showCancel: false
                      });
                    }
                  }
                });
              } else {
                wx.showModal({
                  title: '警告',
                  content: res.msg,
                  showCancel: false
                })
              }
            }
          });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // app.globalData.localSocket.close({
    //   code: 1000,
    //   reason: '退出前台'
    // });
    this.setData({
      useronload: true
    });
    // page.stopHeartBeat()
    // clearTimeout(timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // app.globalData.localSocket.close({
    //   code: 1000,
    //   reason: '退出前台'
    // });
    this.setData({
      useronload: true
    });
    // page.stopHeartBeat()
    // clearTimeout(timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var page = this
    var user = wx.getStorageSync('user_info');
    page.shareSuccess()
    return {
      title: page.data.video.share_title ? page.data.video.share_title : page.data.video.title,
      path: '/pages/course-detail/course-detail?video_id=' + this.data.video_id + '&pid=' + user.user_id,
      imageUrl: page.data.video.share_ico ? page.data.video.share_ico : this.data.video.pic_url,
      success: (res) => {
        console.log("转发成功", res);
      },
      fail: (res) => {
        console.log("转发失败", res);
      }
    }
  },

  //初始化获取信息
  getVideoInfo: function () {
    wx.showLoading({
      title: '加载中',
    })
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.user.video,
      method: "post",
      data: {
        video_id: video_id,
        for_video_id: page.data.for_video_id
      },
      success: function (res) {
        // page.loadComment(video_id);
        page.loadreward(video_id);

        if (res.errcode == 0) {
          page.getCommentList();
          var video = res.data.video;
          if (res.data.status == 0) {
            wx.showModal({
              title: '提示',
              content: '该内容已下架',
              showCancel: false,
              confirmText: '去首页',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index',
                  })
                }
              }
            })
          } else {
            var video = res.data;
            if (video.content) {
              video.content = app.formatImg(video.content)
            }
            if (video.fans_content) {
              video.fans_content = app.formatImg(video.fans_content)
            }
            // WxParse.wxParse("content", "html", content, page, 5);
            page.setData({
              money: res.data.money,
              video: video,
              video_id: res.data.id,
              liveContext: wx.createLivePlayerContext("video-livePlayer")
            });
            if (page.data.video.AUTH == true) {
              page.data.liveContext.src = res.data.live_url
            }

            // page.webSocket();
            page.enter();
            wx.setNavigationBarTitle({
              title: res.data.title,
            })
            // page.addBarrage()
          }
        } else if (res.errcode == 5005) {
          wx.showModal({
            title: '提示',
            content: '该内容已下架',
            showCancel: false,
            confirmText: '去首页',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index',
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });



  },

  play: function (options) {
    wx.redirectTo({
      url: '/pages/video/video?id=' + options.currentTarget.dataset.id,
    })
  },

  //根据密码获取
  getVideoByPassword: function () {
    var page = this;
    var video_id = page.data.video_id;
    if (!page.data.video_password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    wx.showLoading({
      title: "提交中"
    });
    app.request({
      url: api.user.video,
      method: "post",
      data: {
        video_id: video_id,
        password: page.data.video_password
      },
      success: function (res) {
        if (res.errcode == 0) {
          var video = page.data.video;

          if (res.data.AUTH == false) {
            wx.showToast({
              title: "密码错误",
              icon: 'none',
              duration: 2000
            });
          } else {

            video.AUTH = true;
            page.setData({
              video: video
            });
            wx.showToast({
              title: "密码正确",
              icon: 'success',
              duration: 1000
            })
          }
        } else {
          wx.showToast({
            title: "错误",
            icon: 'none',
            duration: 2000
          })
        }
      }
    })

  },

  //购买完成获取
  getVideoByBuy: function () {
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.user.video,
      method: "post",
      data: {
        video_id: video_id,
      },
      success: function (res) {
        if (res.data.errcode == 0) {
          var video = page.data.video;
          video.video_url = res.data.data.video_url;
          page.setData({
            video: video
          })
        } else {
          wx.showToast({
            title: res.data.errmsg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })

  },


  //加载评论
  loadComment: function (id) {
    var page = this;
    is_loading_more = true;
    app.request({
      url: api.user.chat_list,
      data: {
        video_id: id,
        page: 1
      },
      success: function (res) {
        if (res.code == 0) {
          page.setData({
            comment_list: res.data.list,
            comment_count: res.data.row_count,
            page_count: res.data.page_count,
            cc_count: res.data.cc_count,
            scrollview: 'view' + res.data.cc_count,
            iscounting: true
          });

        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.msg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
        is_loading_more = false;
      }
    });
  },

  //加载打赏列表
  loadreward: function (id) {
    var page = this;
    app.request({
      url: api.user.reward_list,
      method: 'POST',
      data: {
        video_id: id,
        page: 1
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            reward_list: res.data.list,
            reward_count: res.data.reward_count,

          });
          if (page.data.reward_list.length > 0) {
            setTimeout(() => {
              // console.log(page.data.reward_list[page.data.reward_list.length])
              page.setData({
                current_reward_index: 'reward_' + page.data.reward_list[page.data.reward_list.length - 1].id
              })

            }, 500)
          }
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.msg,
          showCancel: false
        })
      },
      complete: function () {}
    });
  },

  previewImg: function (e) {
    var page = this;
    var comment_list = page.data.comment_list;
    var index = e.currentTarget.dataset.current;
    var i = e.currentTarget.dataset.i;
    var img_list = comment_list[index].img;
    var current = img_list[i];
    wx.previewImage({
      current: current,
      urls: img_list,
    })
  },
  previewImg_c: function (e) {
    var page = this;
    var comment_list = page.data.comment_list;
    var index = e.currentTarget.dataset.index;
    var i = e.currentTarget.dataset.i;
    var pic = e.currentTarget.dataset.pic;
    var img_list = comment_list[index].children[i].img;
    var current = img_list[pic];
    wx.previewImage({
      current: current,
      urls: img_list,
    })
  },
  formInput: function (e) {
    var page = this;
    var index = e.currentTarget.dataset.index;
    var video = page.data.video
    var form_list = video.form_list;
    form_list[index].value = e.detail.value;
    video.form_list = form_list;
    page.setData({
      video: video
    });
  },
  pause: function () {
    var page = this;
    var video_play = wx.createVideoContext('video');
    video_play.pause();
    page.setData({
      play: false
    });
  },

  timeupdate: function (e) {
    var page = this;
    var video_pay = page.data.video_pay;
    if (page.data.video.is_pay == 0) {
      return;
    }
    var video = wx.createVideoContext('video');
    if (e.detail.currentTime >= video_pay.time) {
      video.seek(0);
      video.pause();
      page.setData({
        play: false
      });
    }
  },

  //绑定打赏金额输入
  getMoney: function (e) {
    var othermoney = e.detail.value;
    var othermoney = othermoney.replace(/^\./g, "");
    var othermoney = othermoney.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    var othermoney = othermoney.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    this.setData({
      othermoney: othermoney
    });
  },

  //绑定密码输入
  getPassword: function (e) {
    this.setData({
      video_password: e.detail.value
    });
  },
  //绑定互动消息输入
  getComment: function (e) {
    var value = e.detail.value;
    if (value.length > 0) {
      this.setData({
        showOrHidden: true,
        clickevent: true,
        comment_data: e.detail.value
      })
    } else {
      this.setData({
        showOrHidden: false,
        clickevent: false,
        state1: e.currentTarget.dataset.key + 1,
      })
    }
    // this.setData({
    //   comment_data: e.detail.value
    // });
  },

  //监听输入框，改变发送按钮颜色
  paidprice: function (e) {
    var value = e.detail.value;
    if (value.length > 0) {
      this.setData({
        showOrHidden: true,
        clickevent: true
      })
    } else {
      this.setData({
        showOrHidden: false,
        clickevent: false,
        state1: e.currentTarget.dataset.key + 1,
      })
    }
  },
  //提交自定义金额
  submitmoney: function (e) {
    var page = this;
    var video = page.data.video;
    var othermoney = page.data.othermoney;
    if (othermoney.indexOf(".") < 0 && othermoney != "") { //此处控制的是如果没有小数点，首位不能为类似于 01、02的金额 
      othermoney = parseFloat(othermoney);
    }
    wx.showLoading({
      title: '提交中',
    })
    this.reward(othermoney);

  },

  //提交密码
  submitpassword: function (e) {
    this.getVideoByPassword(this.data.video_password);
    this.hidePasswordPop();
  },
  //自定义金额打赏
  money: function (options) {
    var money = options.currentTarget.dataset.money;
    wx.showLoading({
      title: '提交中',
    })
    this.reward(money);
  },

  //打赏
  reward: function (price) {
    var page = this;
    var video = page.data.video;

    app.request({
      url: api.order.addreward,
      method: 'POST',
      data: {
        video_id: video.id,
        price: price
      },
      success: function (res) {
        if (res.errcode == 0) {
          app.request({
            url: api.order.get_pay_data,
            method: 'POST',
            data: {
              order_id: res.data.order_id,
              pay_type: 'WECHAT_PAY'
            },
            success: function (result) {
              wx.hideLoading();
              if (result.errcode == 0) {
                var pay_data = result.data;
                wx.requestPayment({
                  timeStamp: pay_data.timeStamp,
                  nonceStr: pay_data.nonceStr,
                  package: pay_data.package,
                  signType: pay_data.signType,
                  paySign: pay_data.paySign,
                  success: function (res) {
                    wx.showToast({
                      title: '打赏成功',
                      icon: 'success'
                    });
                    page.hidepop2();
                    page.hidepop();
                    setTimeout(() => {
                      page.loadreward(video.id);
                    }, 2000);

                  },
                  fail: function (res) {
                    wx.showToast({
                      title: '订单未支付',
                      image: '/images/icon-warning.png'
                    });
                  }
                });
              } else {
                wx.showModal({
                  title: '提示',
                  content: result.msg,
                  showCancel: false
                });
              }
            }
          });
        } else {
          wx.showModal({
            title: '警告',
            content: res.msg,
            showCancel: false
          })
        }
      }
    });
  },


  showModal: function () {
    var page = this;
    page.setData({
      show_modal: true
    });
  },
  closeModal: function () {
    this.setData({
      show_modal: false
    });
  },
  buyVip: function () {
    wx.navigateTo({
      url: '/pages/member/member',
    })
  },
  backIndex: function (e) {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  statechange(e) {
    console.log('live-player code:', e.detail.code)
  },
  error(e) {
    console.error('live-player error:', e.detail.errMsg)
  },

  //点击全屏
  onFullScreenClick: function () {
    var page = this
    page.data.liveContext.requestFullScreen({
      direction: 90,
      success: function (res) {
        page.setData({
          fullScreen: 1
        })
        wx.showToast({
          icon: 'none',
          title: '请点击屏幕退出全屏',
          duration: 2000
        })
      }

    })
  },

  // 全屏
  onFullScreenChange: function (e) {
    console.log(e.detail.fullScreen);
    this.setData({
      fullScreen: e.detail.fullScreen
    })
    wx.showToast({
      icon: 'none',
      title: this.data.fullScreen ? '全屏' : '退出全屏',
    })
  },
  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)

    this.timer = setTimeout(() => {
      this.webSocket();
      this.lockReconnect = false;
    }, 5000);


  },
  //socket定义
  webSocket: function () {
    // 创建Socket
    var that = this;
    console.log(that.data.video)

    app.globalData.localSocket = wx.connectSocket({
      url: that.data.video.ws_url,
      header: {
        'content-type': 'application/json'
      },
      method: 'get',
      success: function (res) {
        console.log('WebSocket连接创建', res);
      },
      fail: function (err) {
        wx.showToast({
          title: '网络异常！',
        })
        console.log(err)
      },
    })


    app.globalData.localSocket.onOpen(res => {
      socketOpen = true;
      this.initSocket();
      console.log('WebSocket连接已打开！readyState=' + app.globalData.localSocket.readyState)
      console.log('监听 WebSocket 连接打开事件。', res)
    })
    app.globalData.localSocket.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
      if (this.data.useronload) {
        console.log('close');
      } else {
        that.reconnect();
        console.log('非正常关闭');
      }

    })
    app.globalData.localSocket.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      that.reconnect()
      // socketOpen = false
    })

    app.globalData.localSocket.onMessage(onMessage => {
      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', onMessage.data)
      if (onMessage.data == "tong") {
        that.startHeartBeat();
        return false;
      }
      var onMessage = JSON.parse(onMessage.data);
      var return_videoid = onMessage.video_id;
      var video_id = that.data.video_id;
      console.log('当前videoid：', video_id);
      var comment_ids = that.data.comment_ids;
      if (return_videoid == video_id) { //如果当前video_id等于推送的video_id
        if (onMessage.content || onMessage.upload_img) {
          comment_ids.push(onMessage.id);
          that.setData({
            comment_ids: comment_ids,
            ['comment_list[' + that.data.comment_list.length + ']']: onMessage,
            current_comment_index: 'comment_' + onMessage.id
          });
        } else if (onMessage.live_user) {
          onMessage.live_user = parseInt(that.data.video.inliveuser) + parseInt(onMessage.live_user);
          that.setData({
            live_user: onMessage
          })
          if (onMessage.join_user) {
            var join_user = onMessage.join_user;
            system_queue.push(join_user);
            that.startQueue();
          }
        }

      }

      console.log(that.data.comment_list);


    })
  },
  /** 
   * 消息队列处理
   */
  startQueue: function () {
    var that = this;
    clearInterval(queue_timer);
    queue_timer = setInterval(function () {
      if (system_queue.length > 0) {
        var join_live_user = system_queue.shift();
        that.setData({
          join_live_user: join_live_user.nickname
        })
      } else {
        that.setData({
          join_live_user: ''
        })
      }

    }, 3000);

  },

  startHeartBeat: function () {

    var that = this;
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    timeoutObj = setTimeout(() => {
      console.log("发送心跳");
      app.globalData.localSocket.send({
        data: JSON.stringify({
          'msg_type': 'heart'
        }),
        success() {
          console.log("心跳成功");
        }
      });
      serverTimeoutObj = setTimeout(() => {
        console.log('心跳断开连接');
        app.globalData.localSocket.close();
      }, 10000);
    }, 10000);

  },


  //初始链接socket
  initSocket: function () {
    var msg = {
      'video_id': this.data.video_id,
      'acct_id': app.globalData.acct_id,
      'openid': wx.getStorageSync("openid")
    }
    console.log('初始化连接', JSON.stringify(msg))
    this.startHeartBeat(); //开始心跳
    app.globalData.localSocket.send({
      data: JSON.stringify(msg)
    })
  },

  //socket发送信息



  //选择图片
  chooseImg: function (e) {
    this.setData({
      comment_data: '',
      comment_img: ''
    });
    app.upload(this.submitImg);
  },
  //提交图片
  submitImg(e) {
    //重连
    var that = this;
    wx.showLoading({
      title: '发送中',
    })
    this.setData({
      comment_img: e.url,
    })
    setTimeout(function () {
      that.sendSocketMessage();
    }, 500);
  },
  //预约
  orderVideo: function (e) {
    console.log(e.detail.formId);
    if (e.detail.formId != 'the formId is a mock one') {

      this.setData({
        formIdString: e.detail.formId + "," + this.data.formIdString
      })
    } else {

    }
    var page = this;
    var video = page.data.video;

    app.request({
      url: api.order.order_video,
      method: 'POST',
      data: {
        video_id: video.id,
        form_id: e.detail.formId
      },
      success: function (res) {
        if (res.errcode == 0) {
          //需要支付 调起支付
          if (res.data.need_pay == 1) {
            app.request({
              url: api.order.get_pay_data,
              method: 'POST',
              data: {
                order_id: res.data.order_id,
                pay_type: 'WECHAT_PAY'
              },
              success: function (result) {
                wx.hideLoading();
                if (result.errcode == 0) {
                  var pay_data = result.data;
                  wx.requestPayment({
                    timeStamp: pay_data.timeStamp,
                    nonceStr: pay_data.nonceStr,
                    package: pay_data.package,
                    signType: pay_data.signType,
                    paySign: pay_data.paySign,
                    success: function (res) {
                      wx.showToast({
                        title: '预约成功',
                        icon: 'success'
                      });
                    },
                    fail: function (res) {
                      wx.showToast({
                        title: '订单未支付',
                        image: '/images/icon-warning.png'
                      });
                    }
                  });
                } else {
                  wx.showModal({
                    title: '提示',
                    content: result.msg,
                    showCancel: false
                  });
                }
              }
            });
          }
          //不需要支付
          else {
            wx.showToast({
              title: res.data.msg,
              icon: 'success'
            });
          }


        } else {
          wx.showModal({
            title: '警告',
            content: res.msg,
            showCancel: false
          })
        }
      }
    });
  },
  //socket发送信息
  //  submitMsg: function () {
  //   var that = this;
  //   if (app.globalData.localSocket.readyState != 1) {
  //     wx.showToast({
  //       title: '发送失败，连接错误',
  //       icon: 'none'
  //     })
  //     return false;
  //   }
  //   that.setData({
  //     comment_img: ""
  //   })
  //   console.log(that.data.clickevent)
  //   if (that.data.clickevent == false) {
  //     wx.showToast({
  //       title: '发送内容不能为空',
  //       icon: 'none'
  //     })
  //   } else if (that.data.comment_data.replace(/(^\s*)|(\s*$)/g, "") == "") {
  //     wx.showToast({
  //       title: '发送内容不能为空',
  //       icon: 'none'
  //     })
  //   } else {
  //     that.sendSocketMessage();
  //   }

  // },
  //socket发送消息
  // sendSocketMessage: function () {
  //   clearTimeout(msgSendTimeoutObj)
  //   var that = this;

  //   var msg = {
  //     'video_id': that.data.video_id,
  //     'content': that.data.comment_data,
  //     'upload_img': that.data.comment_img,
  //     'acct_id': app.globalData.acct_id,
  //     'user_id': wx.getStorageSync("openid")
  //   }

  //   console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
  //   //判断是否连接状态
  //   if (app.globalData.localSocket && app.globalData.localSocket.readyState && app.globalData.localSocket.readyState == 1) {
  //     app.globalData.localSocket.send({
  //       data: JSON.stringify(msg),
  //       success: function (res) {
  //         clearTimeout(msgSendTimeoutObj)
  //         wx.showToast({
  //           title: '发送成功',
  //         });
  //         that.setData({
  //           comment_data: ''
  //         });
  //       },
  //       fail: function (res) {
  //         wx.showToast({
  //           title: '发送失败',
  //           icon: none
  //         })
  //       },
  //     })
  //   } else {
  //     msgSendTimeoutObj = setTimeout(function () {
  //       that.sendSocketMessage();
  //     }, 1000);
  //   }



  // },
  //滚动到底部
  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('#comment_content').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.bottom
      })
    }).exec()
  },
  //历史聊天
  getCommentList: function () {
    var page = this
    app.request({
      url: api.video.live_comment,
      method: 'POST',
      data: {
        video_id: page.data.video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            comment_list: res.data,
          })
          setTimeout(function () {
            if (page.data.comment_list.length > 0) {
              page.setData({
                current_comment_index: 'comment_' + page.data.comment_list[page.data.comment_list.length - 1].id
              })
            }
          }, 1000)
        } else {
          wx.showModal({
            title: '警告',
            content: res.msg,
            showCancel: false
          })
        }
      }
    });
  },

  getMsg(data) {
    var that = this
    var onMessage = JSON.parse(data);
    var return_videoid = onMessage.video_id;
    var video_id = that.data.video_id;
    console.log('当前videoid：', video_id);
    var comment_ids = that.data.comment_ids;
    if (return_videoid == video_id) { //如果当前video_id等于推送的video_id
      if (onMessage.content || onMessage.upload_img) {
        if (comment_ids.indexOf(onMessage.id) == -1) {
          comment_ids.push(onMessage.id);
          that.setData({
            comment_ids: comment_ids,
            ['comment_list[' + that.data.comment_list.length + ']']: onMessage,
            current_comment_index: 'comment_' + onMessage.id
          });
        }
      } else if (onMessage.live_user) {
        // onMessage.live_user = parseInt(that.data.video.inliveuser) + parseInt(onMessage.live_user);
        that.setData({
          live_user: onMessage
        })
        if (onMessage.join_user) {
          var join_user = onMessage.join_user;
          system_queue.push(join_user);
          that.startQueue();
        }
      } else if (onMessage.type == 'reward') {
        if (reward_ids.indexOf(onMessage.id) == -1) {
          reward_ids.push(onMessage.id);
          if(reward_ids.length>2){
            reward_ids.unshift()
          }
          that.setData({
            ['reward_list[' + that.data.reward_list.length + ']']: onMessage,
            current_reward_index: 'reward_' + onMessage.id
          })
        }
        // reward_queue.push(onMessage.damu.content);
        // that.barrage.addData([onMessage.damu])
        // that.addBarrage()
      }

    }

    // console.log(that.data.comment_list);


  },

  //socket发送信息
  submitMsg: function () {
    console.log(1);
    var that = this;
    if (that.data.video.is_comment == 1) {
      wx.showToast({
        title: '您已被禁言，无法发送',
        icon: 'none'
      })
      return false;
    }
    if (that.data.comment_data.replace(/(^\s*)|(\s*$)/g, "") == "") {
      wx.showToast({
        title: '发送内容不能为空',
        icon: 'none'
      })
    } else {
      that.sendSocketMessage();
    }

  },
  //socket发送消息
  sendSocketMessage: function () {

    var that = this;

    var msg = {
      'video_id': that.data.video_id,
      'content': that.data.comment_data,
      'acct_id': app.globalData.acct_id,
      'user_id': wx.getStorageSync("user_info").user_id,
      'nickname': wx.getStorageSync("user_info").nickName,
      'avatar_url': wx.getStorageSync("user_info").avatarUrl,
      'img': that.data.comment_img ? that.data.comment_img : '',
      'type': '',
      'id': ''
    }
    app.request({
      url: api.video.add_live_comment,
      method: "post",
      data: {
        id: that.data.video_id,
        content: that.data.comment_data,
        img: that.data.comment_img,
      },
      success: function (res) {
        if (res.errcode == 0) {
          msg.id = res.data;
          // ROP.Publish(JSON.stringify(msg), that.data.video.app_id + '_' + that.data.video.id);
          that.setData({
            comment_data: '',
            comment_img: '',
            inputInfo: '一起聊天吧~'
          });
          // setInterval(function(){
          //   for (var i = 0; i < 10; i++) {
          //     ROP.Publish(JSON.stringify(msg), that.data.video.app_id + '_' + that.data.video.id);
          //   }
          // },500)


          // page.setData({
          //   haibao: res.data
          // })
          // page.createNewImg()
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });


    // setTimeout(() => {

    // }, 100)

    console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
    // app.globalData.localSocket.send({
    //   data: JSON.stringify(msg),
    //   success: function(res) {
    //     wx.showToast({
    //       title: '发送成功',
    //     });
    //     that.setData({
    //       comment_data: '',
    //       inputInfo: '一起聊天吧~'
    //     });
    //   },
    //   fail: function(res) {
    //     wx.showToast({
    //       title: '发送失败',
    //       icon: none
    //     })
    //   },
    // })


  },

  previewImage(e) {
    console.log(e)
    const dataset = e.currentTarget.dataset
    const current = dataset.current
    const urls = this.data.urls

    wx.previewImage({
      urls: current,
    })
  },
  liveStateChange: function (e) {
    console.log(e.detail.code)
    clearTimeout(play_timer);
    var that = this
    if (e.detail.code == 2004) {
      this.setData({
        hiddenPoster: true
      })
    }

    if (e.detail.code == 2006) {
      this.setData({
        hiddenPoster: false
      })
    }
    if (e.detail.code == -2301) {
      play_timer = setTimeout(() => {
        that.data.liveContext.play()
      }, 10000)
    }
  },
  createHaiBao: function () {
    wx.showLoading({
      title: '创建中',
    })
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.video.share_qrcode,
      method: "post",
      data: {
        id: video_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            haibao: res.data
          })
          page.createNewImg()
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });
  },

  /**
   * 生成二维码
   */

  createNewImg: function () {
    wx.showLoading({
      title: '生成中...',
    })
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    that.GeneratePosters()
    var context = wx.createCanvasContext('mycanvas');
    // const ctx = canvas.getContext('2d');
    context.setFillStyle("#fff");
    context.fillRect(0, 0, width, height);


    //昵称
    context.setFontSize(15);
    context.setFillStyle('#000');
    context.setTextAlign('left');
    context.fillText(wx.getStorageSync('user_info').nickName, 80 * per_width, 60 * per_height, 280 * per_width);
    context.stroke();

    //昵称
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('我发现一个精彩的课程，快来看!', 80 * per_width, 90 * per_height, 280 * per_width);
    context.stroke();

    var text = that.data.video.title;
    //标题
    context.setFontSize(14);
    context.setFillStyle('#333');
    context.setTextAlign('left');


    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < 335 * per_width) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);
    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 220 * per_width) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], 20 * per_width, (560 + b * 24) * per_height, 335 * per_width);
    }

    //提示
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('长按识别图中的小程序码', 180 * per_width, 640 * per_height, 280 * per_width);
    context.stroke();
    //提示
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('查看课程详情', 180 * per_width, 680 * per_height, 280 * per_width);
    context.stroke();
    that.setLogo(context); //绘制头像 
    // context.draw();
    context.fill()
    context.closePath()


  },
  darwAvatarArc: function (ctx, src, x, y, w, h = w) {
    ctx.save();
    ctx.beginPath()
    ctx.arc(x + w / 2, y + h / 2, w / 2, 0, Math.PI * 2, false);
    ctx.clip()
    ctx.drawImage(src, x, y, w, h);
    ctx.restore()
    ctx.draw(true)
  },

  setLogo(ctx) {
    var that = this;
    //that.darwAvatarArc(context, src, 50, 90, 45, 45);
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    var avatarurl_width = 45 * per_width; //绘制的头像宽度
    var avatarurl_heigth = 45 * per_width; //绘制的头像高度
    var avatarurl_x = 20 * per_width; //绘制的头像在画布上的位置
    var avatarurl_y = 40 * per_height; //绘制的头像在画布上的位置
    wx.downloadFile({
      url: that.data.haibao.headimg,
      success: function (res) {
        ctx.save()
        ctx.beginPath() //开始绘制
        ctx.setFillStyle('#fff')
        //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
        ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
        //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因    
        ctx.clip()
        ctx.drawImage(res.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
        ctx.closePath()
        //恢复之前保存的绘图上下文 恢复之前保存的绘图上下文即状态 还可以继续绘制
        ctx.restore()
        //可将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中                                         
        that.setBanner(ctx)
      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })

      }
    })
  },


  setBanner: function (ctx) {
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    wx.downloadFile({
      url: that.data.video.pic_url,
      success: function (res) {
        ctx.drawImage(res.tempFilePath, 20 * per_width, 120 * per_height, 335 * per_width, 335 * per_width);
        ctx.save();
        ctx.restore();
        //绘制奖品名字
        that.setQrcode(ctx)
      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },
  setQrcode(ctx) {
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    var avatarurl_width = 90 * per_width; //绘制的头像宽度
    var avatarurl_heigth = 90 * per_width; //绘制的头像高度
    var avatarurl_x = 60 * per_width; //绘制的头像在画布上的位置
    var avatarurl_y = 600 * per_height; //绘制的头像在画布上的位置
    wx.downloadFile({
      url: that.data.haibao.qr_img,
      success: function (res) {
        ctx.save()
        ctx.beginPath()
        ctx.setFillStyle('#dcdcdc')
        ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
        ctx.clip()
        ctx.drawImage(res.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
        ctx.closePath()
        ctx.restore()
        that.showImg(ctx);
      },
      fail(err) {
        console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })

      }
    })
  },
  showImg(ctx) {
    var that = this;
    that.setData({
      HiddenShare1: false
    })
    ctx.draw(false, function (e) {
      console.log('绘制成功');
      that.saveTempCavans();

    })
  },
  saveTempCavans: function (e) {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      fileType: 'jpg',
      quality: 1,
      success: function (res) {
        // 获得图片临时路径
        that.setData({
          imagePath: res.tempFilePath,
          canvasHidden: true,
          HiddenShare1: false
        })
        that.imageTempPath = res.tempFilePath;
        that.imgSrc = that.imageTempPath;
        setTimeout(function () {
          wx.hideLoading();
        }, 200)
      },
      fail: function (res) {
        setTimeout(function () {
          that.saveTempCavans();
        }, 1000)
      }
    })
  },

  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                HiddenShare1: true
              })
            }
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },
})